package com.hxrfid.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxrfid.common.core.domain.PageQuery;
import com.hxrfid.common.core.page.TableDataInfo;
import com.hxrfid.common.utils.StringUtils;
import com.hxrfid.project.domain.BsProduct;
import com.hxrfid.project.domain.bo.BsProductBo;
import com.hxrfid.project.domain.vo.BsProductVo;
import com.hxrfid.project.mapper.BsProductMapper;
import com.hxrfid.project.service.IBsProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 商品管理Service业务层处理
 *
 * @author hxrfid
 * @date 2025-06-12
 */
@RequiredArgsConstructor
@Service
public class BsProductServiceImpl extends ServiceImpl<BsProductMapper, BsProduct> implements IBsProductService {

    private final BsProductMapper baseMapper;

    /**
     * 查询商品管理
     * @param id 主键ID
     * @return 商品管理
     */
    @Override
    public BsProductVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询订单分组
     * @param type 分组类型：area区域；brand品牌
     * @return 订单分组
     */
    @Override
    public List<BsProductVo> queryAllGroupByType(String type) {
        QueryWrapper<BsProduct> lqw = new QueryWrapper<>();
        if (type.equals("area")) {
            lqw.select("DISTINCT area_id, area");
        } else {
            lqw.select("DISTINCT brand_id,brand");
            lqw.isNotNull("brand_id");
        }
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询商品管理列表
     * @param bo 商品管理对象
     * @param pageQuery 主键ID
     * @return 商品管理列表
     */
    @Override
    public TableDataInfo<BsProductVo> queryPageList(BsProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BsProduct> lqw = buildQueryWrapper(bo);
        Page<BsProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询商品管理列表
     * @param bo 商品管理对象
     * @return 商品管理列表
     */
    @Override
    public List<BsProductVo> queryList(BsProductBo bo) {
        LambdaQueryWrapper<BsProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
    * 组装查询条件
    * @param bo 商品管理对象
    * @return 查询条件
    */
    private LambdaQueryWrapper<BsProduct> buildQueryWrapper(BsProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BsProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getProductType()), BsProduct::getProductType, bo.getProductType());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), BsProduct::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getMainImage()), BsProduct::getMainImage, bo.getMainImage());
        lqw.eq(StringUtils.isNotBlank(bo.getCyclePath()), BsProduct::getCyclePath, bo.getCyclePath());
        lqw.eq(bo.getPrice() != null, BsProduct::getPrice, bo.getPrice());
        lqw.eq(bo.getUnderlinePrice() != null, BsProduct::getUnderlinePrice, bo.getUnderlinePrice());
        lqw.eq(StringUtils.isNotBlank(bo.getUnit()), BsProduct::getUnit, bo.getUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getService()), BsProduct::getService, bo.getService());
        lqw.eq(bo.getInventory() != null, BsProduct::getInventory, bo.getInventory());
        lqw.eq(bo.getSaleNum() != null, BsProduct::getSaleNum, bo.getSaleNum());
        lqw.eq(StringUtils.isNotBlank(bo.getProductDesc()), BsProduct::getProductDesc, bo.getProductDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getSource()), BsProduct::getSource, bo.getSource());
        lqw.eq(StringUtils.isNotBlank(bo.getCredential()), BsProduct::getCredential, bo.getCredential());
        lqw.eq(bo.getBrandId() != null, BsProduct::getBrandId, bo.getBrandId());
        lqw.eq(StringUtils.isNotBlank(bo.getBrand()), BsProduct::getBrand, bo.getBrand());
        lqw.eq(bo.getAreaId() != null, BsProduct::getAreaId, bo.getAreaId());
        lqw.eq(StringUtils.isNotBlank(bo.getArea()), BsProduct::getArea, bo.getArea());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaAddr()), BsProduct::getAreaAddr, bo.getAreaAddr());
        lqw.eq(StringUtils.isNotBlank(bo.getIsSpecial()), BsProduct::getIsSpecial, bo.getIsSpecial());
        lqw.eq(StringUtils.isNotBlank(bo.getIsNew()), BsProduct::getIsNew, bo.getIsNew());
        lqw.eq(StringUtils.isNotBlank(bo.getIsHot()), BsProduct::getIsHot, bo.getIsHot());
        lqw.eq(StringUtils.isNotBlank(bo.getIsScore()), BsProduct::getIsScore, bo.getIsScore());
        // 排序
        if (StringUtils.isNotBlank(bo.getSortParam())) {
            if (StringUtils.isNotBlank(bo.getSortRule())) {
                if ("saleNum".equals(bo.getSortParam())) {
                    if ("desc".equals(bo.getSortRule())) {
                        lqw.orderByDesc(BsProduct::getSaleNum);
                    } else {
                        lqw.orderByAsc(BsProduct::getSaleNum);
                    }
                } else {
                    if ("desc".equals(bo.getSortRule())) {
                        lqw.orderByDesc(BsProduct::getPrice);
                    } else {
                        lqw.orderByAsc(BsProduct::getPrice);
                    }
                }
            }
        } else {
            lqw.orderByDesc(BsProduct::getSaleNum, BsProduct::getPrice);
        }
        return lqw;
    }

    /**
     * 新增商品管理
     * @param bo 商品管理对象
     * @return 是否成功
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean insertByBo(BsProductBo bo) {
        BsProduct add = BeanUtil.toBean(bo, BsProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商品管理
     * @param bo 商品管理对象
     * @return 是否成功
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean updateByBo(BsProductBo bo) {
        BsProduct update = BeanUtil.toBean(bo, BsProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     * @param entity 商品管理对象
     */
    private void validEntityBeforeSave(BsProduct entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商品管理
     * @param ids 主键ID的list
     * @param isValid 是否业务校验
     * @return 是否成功
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
